package com.worklikedance.priceonline;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.worklikedance.model.ExchangeRateItem;
import com.worklikedance.util.Constant;
import com.worklikedance.util.Utilities;

public class ExchangedRateXMLHandler extends DefaultHandler {
	private ArrayList<ExchangeRateItem> mRateArray = null;
	private String mSource;
	private String mUpdateTime;
	private boolean mInDateTime, mInSource;

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		if (localName.equals("ExrateList")) {
			mRateArray = new ArrayList<ExchangeRateItem>();
		} 
		else if (localName.equals("DateTime")) {
			mInDateTime = true;
		} 
		else if (localName.equals("Exrate")) {
			String currencyCode = attributes.getValue("CurrencyCode");
			String currencyName = attributes.getValue("CurrencyName");
			
			double buy = (long)Double.parseDouble(attributes.getValue("Buy"));
			double transfer = (long)Double.parseDouble(attributes.getValue("Transfer"));
			double sell = (long)Double.parseDouble(attributes.getValue("Sell"));
			
			ExchangeRateItem rateItem = new ExchangeRateItem(currencyCode, currencyName, buy, transfer, sell);
			mRateArray.add(rateItem);
		} 
		else if (localName.equals("Source")) {
			mInSource = true;
		} 
	}

	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		if (localName.equals("DateTime")) {
			mInDateTime = false;
		} 
		else if (localName.equals("Source")) {
			mInSource = false;
		}
	}

	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		String chars = new String(ch, start, length);
		chars = chars.trim();
		
		if (mInDateTime) {
//			9/11/2014 5:33:51 AM
			chars = Utilities.convertStringToDateString(chars, "M/d/yyyy h:m:s a", Constant.UPDATED_DATE_TIME_FORMAT);
			mUpdateTime = chars;
		} 
		else if (mInSource) {
			mSource = chars;
		}
	}

	public ArrayList<ExchangeRateItem> getmRateArray() {
		return mRateArray;
	}

	public void setmRateArray(ArrayList<ExchangeRateItem> mRateArray) {
		this.mRateArray = mRateArray;
	}

	public String getmSource() {
		return mSource;
	}

	public void setmSource(String mSource) {
		this.mSource = mSource;
	}

	public String getmUpdateTime() {
		return mUpdateTime;
	}

	public void setmUpdateTime(String mUpdateTime) {
		this.mUpdateTime = mUpdateTime;
	}
}
